package com.tfd.blog.controller;

import com.tfd.blog.domain.Label;
import com.tfd.blog.exception.BlogExceptionCode;
import com.tfd.blog.filter.NeedLogin;
import com.tfd.blog.repository.LabelRepository;
import com.tfd.blog.service.LabelService;
import com.tfd.blog.utlis.JsonResult;
import com.tfd.blog.utlis.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author TangFD
 * @since 2019/5/7.
 */
@Slf4j
@RestController
@RequestMapping("/label")
public class LabelController {

    @Resource
    private LabelRepository labelRepository;
    @Resource
    private LabelService labelService;

    @NeedLogin
    @RequestMapping("/manage/save")
    public JsonResult save(@RequestBody Label label) {
        JsonResult result = new JsonResult();
        if (label == null) {
            result.setMessage(BlogExceptionCode.ILLEGAL_ARGUMENT.name(), false);
            return result;
        }

        try {
            label.setCreateDate(new Date());
            labelRepository.save(label);
            return new JsonResult();
        } catch (Exception e) {
            result.setMessage(BlogExceptionCode.SYSTEM_ERROR.name(), false);
            return result;
        }
    }

    @NeedLogin
    @RequestMapping("/manage/page")
    public JsonResult<Page> page(String keyword, @RequestBody Page<Label> page) {
        if (page == null) {
            return new JsonResult<>(BlogExceptionCode.ILLEGAL_ARGUMENT.name(), false);
        }

        Sort sort = Sort.by(Sort.Order.desc("createDate"));
        PageRequest pageable = PageRequest.of(page.getPageNum() - 1, page.getPageSize(), sort);
        org.springframework.data.domain.Page<Label> labelPage;
        if (StringUtils.isEmpty(keyword)) {
            labelPage = labelRepository.findAll(pageable);
        } else {
            labelPage = labelRepository.findByNameLike("%" + keyword + "%", pageable);
        }

        page.setTotal(labelPage.getTotalElements());
        page.setList(labelPage.getContent());
        return new JsonResult<>(page);
    }

    @NeedLogin
    @DeleteMapping("/manage/delete/{id}")
    public JsonResult delete(@PathVariable("id") String id) {
        try {
            labelService.deleteById(id);
            return new JsonResult();
        } catch (Exception e) {
            return new JsonResult(null, false);
        }
    }
}
